var request = require('request')
var moment = require('moment')
var md5 = require('md5')

moment.locale('zh-cn')

module.exports = {

  config: {},

  callback: Function,

  clockIn(config, callback) {
    this.config = config
    this.callback = callback
    // setTimeout(()=> {
    //   callback(this.config)
    // }, 1000)
    // console.log(this.config.id)
    this.getKeyCode(this.config.id)
  },

  getKeyCode(id) {
    request.post({
      url: 'https://portal.hiido.com/restful/card/keycode',
      form: {
        code: id
      }
    }, (error, response, body) => {
      var keyCode = body
      this.checkIn(keyCode)
    });
  },

  checkIn(keyCode) {
    var time = +new Date()
    var phone = this.config.phone
    var longitude = "113.377" + parseInt(190*Math.random()+800)
    var code = this.config.id
    var os = "ios"
    var latitude = "23.122" + parseInt(190*Math.random()+200)

    var str = code+phone+time+keyCode
    var verify = md5(md5(str))

    var data = {
      "phone" : phone,
      "verify" : verify,
      "time" : time+"",
      "longitude" : longitude,
      "code" : code,
      "os" : os,
      "latitude" : latitude
    }

    request({
      method: 'POST',
      url: 'https://portal.hiido.com/restful/card/phone/attendance',
      form: {
        json: JSON.stringify(data)
      }
    },

    (error, response, body)=> {
      if (error) {
        return console.error('upload failed:', error)
      }

      var json = JSON.parse(body)
      var desc = decodeURI(json.desc)
      // console.log(desc)
      this.callback(desc)

    })
  }

}